package cn.edu.hqu.example.bj.experiment_4;

import android.os.Binder;
import android.support.v7.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity<BinderService> extends AppCompatActivity {

    //声明按钮
    Button bind;
    Button unbind;
    Button getServiceStatus;

    //保持所启动的service的ibinder对象
    BindService.MyBinder myBinder;

    //定义一个SericeConnection对象
    private ServiceConnection connection=new ServiceConnection() {
        //连接成功时
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("~~~Connected~~~");
            myBinder=(BindService.MyBinder)service;
        }

        //连接失败时
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("~~~Disconnected~~~");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取程序界面中的bind、unbind、getServiceStatus按钮
        bind=(Button)findViewById(R.id.bindButton);
        unbind=(Button)findViewById(R.id.unbindButton);
        getServiceStatus=(Button)findViewById(R.id.getServiceStatusButton);

        //创建启动的service的intent
        final Intent intent=new Intent(MainActivity.this,BindService.class);

        //监听bind按钮点击
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //绑定指定Service
                bindService(intent,connection,BIND_AUTO_CREATE);
            }
        });

        //监听unbind按钮的点击
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解除绑定service
                unbindService(connection);
            }
        });

        //监听getServiceStatus按钮点击
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取并显示Service的count值
                Toast.makeText(MainActivity.this,"Service的count值的："+ myBinder.getCount(),
                Toast.LENGTH_SHORT).show();
            }
        });
    }
}
